package org.netbeans.ddlmodule;

import java.io.Serializable;
import java.util.logging.Logger;
import org.apache.ddlutils.Platform;
import org.apache.ddlutils.io.DatabaseIO;
import org.apache.ddlutils.model.Database;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.apache.ddlutils.PlatformFactory;
//import org.openide.util.Utilities;
import org.apache.derby.jdbc.ClientDataSource;

/**
 * Top component which displays something.
 */
final class DDLTopComponent extends TopComponent {

    private static DDLTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    private static final String PREFERRED_ID = "DDLTopComponent";

    private DDLTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(DDLTopComponent.class, "CTL_DDLTopComponent"));
        setToolTipText(NbBundle.getMessage(DDLTopComponent.class, "HINT_DDLTopComponent"));
//        setIcon(Utilities.loadImage(ICON_PATH, true));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        GenerateDB = new javax.swing.JButton();

        org.openide.awt.Mnemonics.setLocalizedText(GenerateDB, "Generate DB");
        GenerateDB.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                GenerateDBMouseClicked(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(158, 158, 158)
                .add(GenerateDB)
                .addContainerGap(149, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(108, 108, 108)
                .add(GenerateDB)
                .addContainerGap(169, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

private void GenerateDBMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_GenerateDBMouseClicked
            String filename = "/Users/David/xmltodb.xml";
            
            Database targetModel = new DatabaseIO().read(filename);
            
            ClientDataSource dataSource = new ClientDataSource();
            dataSource.setDatabaseName("ddlutilsDB");
            dataSource.setConnectionAttributes("create=true");
//            BasicDataSource dataSource = new BasicDataSource();

//            dataSource.setUrl("jdbc:derby://localhost:1527/ddlutilsDB;create=true");
//            dataSource.setDriverClassName(org.apache.derby.jdbc.ClientDriver.class.getName());
            
            Platform platform = PlatformFactory.createNewPlatformInstance(dataSource);
            boolean alterDb = false;
            if (alterDb) {
                platform.alterTables(targetModel, false);
            } else {

                platform.createTables(targetModel, true, true);
            }

}//GEN-LAST:event_GenerateDBMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton GenerateDB;
    // End of variables declaration//GEN-END:variables

    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized DDLTopComponent getDefault() {
        if (instance == null) {
            instance = new DDLTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the DDLTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized DDLTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(DDLTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof DDLTopComponent) {
            return (DDLTopComponent)win;
        }
        Logger.getLogger(DDLTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID +
                "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    public @Override int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    public @Override void componentOpened() {
        // TODO add custom code on component opening
    }

    public @Override void componentClosed() {
        // TODO add custom code on component closing
    }

    /** replaces this in object stream */
    public @Override Object writeReplace() {
        return new ResolvableHelper();
    }

    protected @Override String preferredID() {
        return PREFERRED_ID;
    }

    final static class ResolvableHelper implements Serializable {
        private static final long serialVersionUID = 1L;
        public Object readResolve() {
            return DDLTopComponent.getDefault();
        }
    }

}
